/*
 * Copyright 2016 atnoce.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.view;

import com.atnoce.Start;
import com.atnoce.core.SecurityController;
import com.atnoce.db.ConfigDao;
import com.atnoce.db.DbUtils;
import com.atnoce.net.BasicNetService;
import com.atnoce.util.Cache;
import com.atnoce.util.InitContext;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.util.Pair;
import org.apache.commons.lang.StringUtils;

/**
 * FXML Controller class
 *
 * @author Administrator
 */
public class BeforeLoginController implements Initializable {
    @FXML
    private Button createMainPassBtn;
    @FXML
    private Button loginColudServiceBtn;

    private Start start;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        createMainPassBtn.setOnAction(e->createMainPass());
        loginColudServiceBtn.setOnAction(e->loginColudService());
    }   
    public void setStart(Start start){
        this.start=start;
    }
    /**
     * 创建主密码
     */
    private void createMainPass(){
            Dialog<Pair<String,String>> dialog=new Dialog<>();
            dialog.setTitle("创建主密码");
            dialog.setHeaderText("正在创建主密码");
            dialog.setGraphic(new ImageView(this.getClass().getResource("image/createMainPass.png").toString()));
            
            ButtonType createBtnType=new ButtonType("创建",ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().addAll(createBtnType,ButtonType.CANCEL);
            
            GridPane grid=new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new Insets(20,150,10,10));
            
            PasswordField oldPass=new PasswordField();
            oldPass.setPromptText("输入主密码");
            PasswordField newPass=new PasswordField();
            newPass.setPromptText("重复主密码");
            
            grid.add(new Label("输入主密码:"), 0, 0);
            grid.add(oldPass, 1, 0);
            grid.add(new Label("重复主密码:"), 0, 1);
            grid.add(newPass, 1, 1);
            
            Node lookupButton = dialog.getDialogPane().lookupButton(createBtnType);
            lookupButton.setDisable(true);
            
            newPass.textProperty().addListener((observable,oldValue,newValue)->{
                lookupButton.setDisable(!StringUtils.equals(oldPass.getText(), newValue));
            });
            
            dialog.getDialogPane().setContent(grid);
            
            Platform.runLater(()->oldPass.requestFocus());
            
            dialog.setResultConverter(dialogButton->{
                if(dialogButton==createBtnType){
                    return new Pair<>(oldPass.getText(),newPass.getText());
                }
                return null;
            });
            
            Optional<Pair<String, String>> result = dialog.showAndWait();
            result.ifPresent(consumer->{
                String oldp=consumer.getKey();
                String newp=consumer.getValue();
                Alert alert;
                
                if(oldp.length()<1){
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("创建失败");
                    alert.setContentText("密码不能为空");
                    return;
                }
                //openAll();
                //初始化数据库
                try{
                    DbUtils.initTables();
                }catch(ClassNotFoundException e){
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("初始化数据库失败");
                    alert.setContentText("找不到数据库驱动！");
                    alert.showAndWait();
                }catch(SQLException e){
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("初始化数据库失败");
                    alert.setContentText("发生内部错误！");
                    alert.showAndWait();
                }
                //加密主密码
                String newMainPass=SecurityController.getSecurityInstence().encryptionMain(newp);
                //保存主密码
                ConfigDao cd=new ConfigDao();
                try {
                    if(cd.updateMainPass(newMainPass)){
                        start.initLoginLayout(null);
                    }else{
                        
                    }
                    //显示登录界面
                } catch (SQLException ex) {
                    alert=new Alert(AlertType.ERROR);
                    alert.setHeaderText("更新密码未成功");
                    alert.setContentText("更新密码时发生SQL异常!");
                    alert.show();
                }catch(ClassNotFoundException e){
                    alert=new Alert(AlertType.ERROR);
                    alert.setHeaderText("更新密码未成功");
                    alert.setContentText("找不到数据库驱动!");
                    alert.show();
                }
                 
                try {
                    //更新配置文件
                    InitContext.updateProperties("fdb", "false");
                    InitContext.updateProperties("fstart", "false");
                } catch (IOException ex) {
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("更新配置文件失败");
                    alert.setContentText("更新系统配置文件发生异常!");
                    alert.show();
                }
                    
                    //更新内存
                    Cache.proMap.put("fstart", "false");
                    Cache.proMap.put("fdb", "false");
               
            });
    }
    /**
     * 登录云服务
     */
    private void loginColudService(){
        //服务端如果没有密码，那么应该如何绑定云账号？
        //不用管账号，错误的密码库无法打开
            Dialog<Pair<String,String>> dialog=new Dialog<>();
            dialog.setTitle("登录云账号");
            dialog.setHeaderText("请填写云账号信息");
            dialog.setGraphic(new ImageView(this.getClass().getResource("image/2_1.jpg").toString()));
            
            ButtonType createBtnType=new ButtonType("绑定",ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().addAll(createBtnType,ButtonType.CANCEL);
            
            GridPane grid=new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new Insets(20,150,10,10));
            
            TextField coludAccount=new TextField();
            coludAccount.setPromptText("输入云账号");
            TextField bindCode=new TextField();
            bindCode.setPromptText("输入绑定号");
            
            grid.add(new Label("云账号:"), 0, 0);
            grid.add(coludAccount, 1, 0);
            grid.add(new Label("绑定号:"), 0, 1);
            grid.add(bindCode, 1, 1);
            
            //Node lookupButton = dialog.getDialogPane().lookupButton(createBtnType);
            //lookupButton.setDisable(true);
            
            
            dialog.getDialogPane().setContent(grid);
            
            Platform.runLater(()->coludAccount.requestFocus());
            
            dialog.setResultConverter(dialogButton->{
                if(dialogButton==createBtnType){
                    return new Pair<>(coludAccount.getText(),bindCode.getText());
                }
                return null;
            });
            
            Optional<Pair<String, String>> result = dialog.showAndWait();
            result.ifPresent(consumer->{
                String account=consumer.getKey();
                String code=consumer.getValue();
                Alert alert;
                
                if(StringUtils.isBlank(account)){
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("绑定失败");
                    alert.setContentText("云账号不能为空!");
                    alert.showAndWait();
                    return;
                }
                //openAll();
                //校验云账号
                BasicNetService basicNetService=new BasicNetService();
                try {
                    String bindResult = basicNetService.bindColudAccount(account);
                    if(StringUtils.equals(bindResult, "true")){
                        //先同步密码库过来
                        Map<String, Object> sync = basicNetService.synchDowload(account);
                         if((boolean)sync.get("flag")){
                             start.initLoginLayout(account);
                             
                         }else{
                             //同步发生问题
                            alert=new Alert(AlertType.WARNING);
                            alert.setTitle("错误");
                            alert.setHeaderText("同步密码库失败!");
                            alert.setContentText("同步发生问题1"+sync.get("msg"));
                            alert.showAndWait();
                            return;
                         }
                        
                    }else if(StringUtils.equals(bindResult, "false")){
                        alert=new Alert(Alert.AlertType.ERROR);
                        alert.setHeaderText("绑定失败");
                        alert.setContentText("账号不存在!");
                        alert.showAndWait();
                    }else{
                        alert=new Alert(Alert.AlertType.ERROR);
                        alert.setHeaderText("绑定失败");
                        alert.setContentText("绑定出现问题!"+bindResult);
                        alert.showAndWait();
                    }
                    
                } catch (IOException ex) {
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("绑定失败");
                    alert.setContentText("无法访问网络主机!"+ex.getMessage());
                    alert.showAndWait();
                }
                //加密主密码
                //String newMainPass=SecurityController.getSecurityInstence().encryptionMain(newp);
               
            });
    }
    
}
